package com.ltx.bugseeker.controller;

import com.ltx.bugseeker.common.Result;
import com.ltx.bugseeker.common.ResultCode;
import com.ltx.bugseeker.entity.Project;
import com.ltx.bugseeker.entity.ProjectMember;
import com.ltx.bugseeker.service.IProjectService;
import com.ltx.bugseeker.service.IProjectMemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import cn.dev33.satoken.stp.StpUtil;

/**
 * 项目管理控制器
 * 提供项目和项目成员的增删改查接口
 *
 * @author ltx
 * @since 2025-10-20
 */
@Slf4j
@RestController
@RequestMapping("/api/projects")
@RequiredArgsConstructor
public class ProjectController {

    private final IProjectService projectService;
    private final IProjectMemberService projectMemberService;

    /**
     * 创建项目
     */
    @PostMapping
    public Result<Project> createProject(@RequestBody Project project) {
        try {
            // 检查用户是否已登录
            if (!StpUtil.isLogin()) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户未登录");
            }
            
            // 获取当前登录用户ID
            Long currentUserId = StpUtil.getLoginIdAsLong();
            
            // 设置项目所有者为当前用户
            project.setOwnerId(currentUserId);
            
            // 设置创建人和更新人为当前用户
            project.setCreateBy(currentUserId);
            project.setUpdateBy(currentUserId);
            
            boolean saved = projectService.save(project);
            if (saved) {
                // 项目创建成功后，自动将创建者添加为项目成员
                ProjectMember member = new ProjectMember();
                member.setProjectId(project.getId());
                member.setUserId(currentUserId);
                member.setRole(1); // 项目所有者
                member.setCreateBy(currentUserId);
                member.setUpdateBy(currentUserId);
                projectMemberService.save(member);
                
                return Result.success(project);
            } else {
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            log.error("创建项目失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "创建项目失败: " + e.getMessage());
        }
    }

    /**
     * 更新项目
     */
    @PutMapping("/{id}")
    public Result<Project> updateProject(@PathVariable Long id, @RequestBody Project project) {
        try {
            // 检查用户是否已登录
            if (!StpUtil.isLogin()) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户未登录");
            }
            
            // 获取当前登录用户ID
            Long currentUserId = StpUtil.getLoginIdAsLong();
            
            project.setId(id);
            // 设置更新人为当前用户
            project.setUpdateBy(currentUserId);
            
            boolean updated = projectService.updateById(project);
            if (updated) {
                return Result.success(projectService.getById(id));
            } else {
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            log.error("更新项目失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "更新项目失败: " + e.getMessage());
        }
    }

    /**
     * 删除项目
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteProject(@PathVariable Long id) {
        try {
            // 检查用户是否已登录
            if (!StpUtil.isLogin()) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户未登录");
            }
            
            boolean removed = projectService.removeById(id);
            if (removed) {
                return Result.success();
            } else {
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            log.error("删除项目失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "删除项目失败: " + e.getMessage());
        }
    }

    /**
     * 获取项目详情
     */
    @GetMapping("/{id}")
    public Result<Project> getProject(@PathVariable Long id) {
        try {
            Project project = projectService.getById(id);
            if (project != null) {
                return Result.success(project);
            } else {
                return Result.error(ResultCode.NOT_FOUND);
            }
        } catch (Exception e) {
            log.error("获取项目详情失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "获取项目详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取项目列表
     */
    @GetMapping
    public Result<List<Project>> listProjects() {
        try {
            List<Project> projects = projectService.list();
            return Result.success(projects);
        } catch (Exception e) {
            log.error("获取项目列表失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "获取项目列表失败: " + e.getMessage());
        }
    }

    /**
     * 添加项目成员
     */
    @PostMapping("/{projectId}/members")
    public Result<ProjectMember> addProjectMember(@PathVariable Long projectId, @RequestBody ProjectMember member) {
        try {
            // 检查用户是否已登录
            if (!StpUtil.isLogin()) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户未登录");
            }
            
            // 获取当前登录用户ID
            Long currentUserId = StpUtil.getLoginIdAsLong();
            
            member.setProjectId(projectId);
            // 设置创建人和更新人为当前用户
            member.setCreateBy(currentUserId);
            member.setUpdateBy(currentUserId);
            
            boolean saved = projectMemberService.save(member);
            if (saved) {
                return Result.success(member);
            } else {
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            log.error("添加项目成员失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "添加项目成员失败: " + e.getMessage());
        }
    }

    /**
     * 删除项目成员
     */
    @DeleteMapping("/{projectId}/members/{memberId}")
    public Result<Void> removeProjectMember(@PathVariable Long projectId, @PathVariable Long memberId) {
        try {
            // 检查用户是否已登录
            if (!StpUtil.isLogin()) {
                return Result.error(ResultCode.UNAUTHORIZED.getCode(), "用户未登录");
            }
            
            boolean removed = projectMemberService.removeById(memberId);
            if (removed) {
                return Result.success();
            } else {
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            log.error("删除项目成员失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "删除项目成员失败: " + e.getMessage());
        }
    }

    /**
     * 获取项目成员列表
     */
    @GetMapping("/{projectId}/members")
    public Result<List<ProjectMember>> listProjectMembers(@PathVariable Long projectId) {
        try {
            List<ProjectMember> members = projectMemberService.list();
            return Result.success(members);
        } catch (Exception e) {
            log.error("获取项目成员列表失败", e);
            return Result.error(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "获取项目成员列表失败: " + e.getMessage());
        }
    }
}